<?
##########################################################################
#		DOCUMENTATION
##########################################################################
# signin script. Start the session and handle the cookies. When everything is
# set returns to view.php
#
# © LiberLab group, 2011
##########################################################################

require_once("dataStructure/user.php");
require_once("dynamic/base/sendData.php");

session_start();

class Signin extends SendData{
	public function __construct() {
		parent::__construct("signin");
	}
	
	public function main(){
		#nickname, password1, password2, email, name, surname
		$nickname = strtolower(getParam("nickname", ""));
		$password1 = getParam("password1", "");
		$password2 = getParam("password2", "");
		$email = getParam("email", "");
		$authorName = getParam("name", NULL);
		$authorSurname = getParam("surname", NULL);
		
		$query = $this->queryBuilder(array("nickname", "password1", "password2", "email", "name", "surname",
										  "no_user", "no_password", "no_email", "no_match", "generic", "nickname_over"));
										  
		if ($nickname and $password1 and $password2 and $email and $this->mailCheck($email) and $password1==$password2){
			$userClass = new User();
			$userId = $userClass->getUserId($nickname)->id;
			# there's already an user with the nickname given
			if ($userId){
				$this->checkInsert(1, "&nickname_over=1");
			}else{
				$insertionResult = $userClass->userInsert($nickname, $password1, $email, NULL, $authorName, $authorSurname);
				if ($insertionResult){
					$passwordEncrypted = $userClass->encryptPassword($password1);
					$this->setSession("nickname", $nickname);
					$this->setSession("password", $passwordEncrypted);
					return $this->redirect(preg_replace("/page=([^&$]*?)(&|$)/", "page=signin_success\\2", $query));
				}else{
					$this->checkInsert(1, "&generic=1");
				}
			}
		}else{
			$this->checkInsert((!$nickname), "&no_user=1");
			$this->checkInsert((!($password1 and $password2)), "&no_password=1");
			$this->checkInsert((!($email and $this->mailCheck($email))), "&no_email=1");
			$this->checkInsert(($password1 != $password2), "&no_match=1");
			
		}
		return $this->redirect($this->queryFinalize($checkArray, $query)); 
	}

	public function __destruct() {
		parent::__destruct();
	}
};

$signin = new Signin();
$signin->main();

?>
